package com.intelligencesoft.pss.auth;

import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.intelligencesoft.pss.entity.base.UserInfo;
import com.intelligencesoft.pss.utils.auth.Base64Util;
import com.intelligencesoft.pss.web.ServletUtil;

@Component
public class LoginUtil {
	@Autowired
	private ServletUtil web;
	private Cookie cookie = new SimpleCookie();
	
	@Autowired
	@Qualifier("configProperties")
	private static Properties properties;

	/**
	 * 从cookie中获取用户登录信息
	 * @return {"id":"1","email":"a@a.a",......}
	 */
	public String getLoginInfo() {
		cookie.setName(LoginType.LOGINCOOKIE);
		String info = cookie.readValue(web.getRequest(), null);
		if(info==null){
			info = web.getRequest().getParameter("tokenId");
		}
		return Base64Util.decode(info);
	}

	/**
	 * 将用户登录后信息写入cookie
	 * @param info
	 * @param response
	 */
	public void setLoginInfo(String info, HttpServletResponse response) {
		cookie.setName(LoginType.LOGINCOOKIE);
		cookie.setPath("/");
		cookie.setValue(Base64Util.encode(info));
		cookie.saveTo(web.getRequest(), response);
	}

	/**
	 * 根据属性名称获取用户登录信息
	 * @param field
	 * @return 属性值
	 */
	@SuppressWarnings("unchecked")
	public <T>T getLoginInfo(String field) {
		String info = getLoginInfo();
		if (null != info && !"".equals(info)) {
			try {
				Map<String,Object> map = new ObjectMapper().readValue(info, Map.class);
				return (T) map.get(field);
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
		return null; 
	}

	/**
	 * 获取登录用户信息对象
	 * @return userinfo
	 */
	public UserInfo getLoginUser() {
		String info = getLoginInfo();
		if (null != info && !"".equals(info)) {
			try {
				return new ObjectMapper().readValue(info, UserInfo.class);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 创建tokenid：将用户登录信息info编码后成为tokenid
	 * @param info
	 * @return tokenid
	 */
	public String createTokenId(String info) {
		return Base64Util.encode(info);
	}
	
}
